<!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <!--
    noVNC example: lightweight example using minimal UI and features

    This is a self-contained file which doesn't import WebUtil or external CSS.

    Copyright (C) 2019 The noVNC Authors
    noVNC is licensed under the MPL 2.0 (see LICENSE.txt)
    This file is licensed under the 2-Clause BSD license (see LICENSE.txt).

    Connect parameters are provided in query string:
        http://example.com/?host=HOST&port=PORT&scale=true
    -->
    <title>noVNC</title>

    <style>
        body {
            margin: 0;
            background-color: dimgrey;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        html {
            height: 100%;
        }

        #top_bar {
            background-color: #6e84a3;
            color: white;
            font: bold 12px Helvetica;
            padding: 6px 5px 4px 5px;
            border-bottom: 1px outset;
        }

        #status {
            text-align: center;
        }

        #sendCtrlAltDelButton, #clipboard {
            position: fixed;
            top: 0px;
            right: 0px;
            border: 1px outset;
            padding: 5px 5px 4px 5px;
            cursor: pointer;
        }

        #screen {
            flex: 1;
            /* fill remaining space */
            overflow: hidden;
        }

        #screen>div {
            height: 100%;
        }
        .noVNC_vcenter {
            left: 50% !important; 
            transform: translateX(-50%) !important;
        }
        .noVNC_panel {
            transform: translateX(0) !important;
            width: 600px !important;
            height: 463px !important;
            border-radius: 10px !important;
            padding: 30px !important;
            overflow: hidden !important;
        }
        .noVNC_panel textarea {
            width: 100% !important;
            height: 173px;
            background: #F2F7FA;
            border-radius: 10px;
            resize: none;
        }
        .flex-row-between{
            display: flex !important;
            justify-content: space-between;
            flex-direction: row;
            align-items: center;
        }
        .flex-row-end{
            display: flex !important;
            justify-content: flex-end;
            flex-direction: row;
            align-items: center;
        }
        .main-btn {
            cursor: pointer;
            background-color: #FF6200;
            min-width: 120px;
            height: 40px;
            padding: 10px;
            text-align: center;
            line-height: 20px;
            font-size: 16px;
            color: white;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .info-btn {
            cursor: pointer;
            min-width: 120px;
            height: 40px;
            padding: 10px;
            text-align: center;
            line-height: 16px;
            font-size: 16px;
            color: #808080;
            border-radius: 4px;
            border: 2px solid #808080;
            box-sizing: border-box;
        }
    </style>

    <link rel="stylesheet" href="app/styles/base.css">
    <link rel="stylesheet" href="app/styles/input.css">

    <!-- <script type="text/javascript" src="./core/util/logging.js"></script> -->
    <script src="./layui/layui.js" charset="utf-8"></script>
    <script type="module" crossorigin="anonymous">
        // RFB holds the API to connect and communicate with a VNC server
        import RFB from './core/rfb.js';
        import * as Log from './core/util/logging.js';

        let rfb;
        let desktopName;

        var layer
        var element
        layui.use('layer', function () {
            layer = layui.layer;
        });
        layui.use('element', function () {
            element = layui.element;
        });

        // When this function is called we have
        // successfully connected to a server
        function connectedToServer(e) {
            //status("Connected to " + desktopName);
            status("已连接到 " + desktopName);
        }

        // This function is called when we are disconnected
        function disconnectedFromServer(e) {
            if (e.detail.clean) {
                //status("Disconnected");
                status("已断开，正在尝试重连");
                setInterval(() => location.reload(), 5000)
            } else {
                //status("Something went wrong, connection is closed");
                status("出问题了，连接已关闭，继续尝试重连");
                setInterval(() => location.reload(), 5000)
            }
        }

        // When this function is called, the server requires
        // credentials to authenticate
        function credentialsAreRequired(e) {
            const password = prompt("Password Required:");
            rfb.sendCredentials({ password: password });
        }

        // When this function is called we have received
        // a desktop name from the server
        function updateDesktopName(e) {
            desktopName = e.detail.name;
        }

        // Since most operating systems will catch Ctrl+Alt+Del
        // before they get a chance to be intercepted by the browser,
        // we provide a way to emulate this key sequence.
        function sendCtrlAltDel() {
            rfb.sendCtrlAltDel();
            return false;
        }

        function openClipboardPanel() {
            document.getElementById('noVNC_clipboard')
                .classList.add("noVNC_open");
            document.getElementById('noVNC_clipboard_text').value = "";
        }

        function closeClipboardPanel() {
            document.getElementById('noVNC_clipboard')
                .classList.remove("noVNC_open");
        }

        function toggleClipboardPanel() {
            if (document.getElementById('noVNC_clipboard').classList.contains("noVNC_open")) {
                closeClipboardPanel();
                if(document.getElementById('noVNC_clipboard_text').value) {
                    // alert('信息已经复制')
                    layer.msg('信息已复制，可粘贴至远程桌面', {
                        icon: 1,
                        time: 3000 //2秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        closeClipboardPanel();
                    });
                }
            } else {
                openClipboardPanel();
            }
        }

        function addClipboardHandlers() {
            document.getElementById("noVNC_clipboard_text")
                .addEventListener('change', clipboardSend);
        }

        // Show a status text in the top bar
        function status(text) {
            document.getElementById('status').textContent = text;
        }

        // This function extracts the value of one variable from the
        // query string. If the variable isn't defined in the URL
        // it returns the default value instead.
        function readQueryVariable(name, defaultValue) {
            // A URL with a query parameter can look like this:
            // https://www.example.com?myqueryparam=myvalue
            //
            // Note that we use location.href instead of location.search
            // because Firefox < 53 has a bug w.r.t location.search
            const re = new RegExp('.*[?&]' + name + '=([^&#]*)'),
                match = document.location.href.match(re);

            if (match) {
                // We have to decode the URL since want the cleartext value
                return decodeURIComponent(match[1]);
            }

            return defaultValue;
        }

        // document.getElementById('sendCtrlAltDelButton')
        //     .onclick = sendCtrlAltDel;

        document.getElementById('clipboard')
            .onclick = toggleClipboardPanel;
        document.getElementById('close')
            .onclick = closeClipboardPanel;
        document.getElementById('main-btn')
            .onclick = toggleClipboardPanel;
        document.getElementById("noVNC_clipboard_text")
            .addEventListener('blur', toggleClipboardPanel);
        // document.getElementById('info-btn')
        //     .onclick = toggleClipboardPanel;

        document.getElementById("noVNC_clipboard_text")
            .addEventListener('change', clipboardSend);

        // Read parameters specified in the URL query string
        // By default, use the host and port of server that served this file
        const host = readQueryVariable('host', window.location.hostname);
        let port = readQueryVariable('port', window.location.port);
        const password = readQueryVariable('password');
        const path = readQueryVariable('path', 'websockify');

        // | | |         | | |
        // | | | Connect | | |
        // v v v         v v v

        status("Connecting");

        // Build the websocket URL used to connect
        let url;
        if (window.location.protocol === "https:") {
            url = 'wss';
        } else {
            url = 'ws';
        }
        url += '://' + host;
        if (port) {
            url += ':' + port;
        }
        url += '/' + path;

        // Creating a new RFB object will start a new connection

        //get pcode
        var queryString = window.location.search;
        var urlParams = new URLSearchParams(decodeURIComponent(queryString));
        var param1 = urlParams.get('pcode');
        rfb = new RFB(document.getElementById('screen'), url,
            { credentials: { password: param1.slice(param1.indexOf('A'), param1.indexOf('nr') + 2) } });
        // { credentials: { password: password } });

        // Add listeners to important events from the RFB module
        rfb.addEventListener("connect", connectedToServer);
        rfb.addEventListener("disconnect", disconnectedFromServer);
        rfb.addEventListener("credentialsrequired", credentialsAreRequired);
        rfb.addEventListener("desktopname", updateDesktopName);
        rfb.addEventListener("clipboard", clipboardReceive);
        rfb.addEventListener('paste', (event) => {
            debugger
        });

        // Set parameters that can be changed on an active connection
        rfb.viewOnly = readQueryVariable('view_only', false);
        // rfb.scaleViewport = readQueryVariable('scale', false);
        rfb.scaleViewport = true; // 启用缩放视口
        rfb.resizeSession = true; // 启用重新调整大小
        rfb.scaleDisplay = true; // 启用显示缩放
        rfb.clipViewport = true; // 剪切视口以适应窗口大小
        // rfb.autoResize = 'scale'; // 使用缩放模式自动调整大小
        // rfb.addEventListener('resize', function (event) {
        //     // 这将监听调整大小事件，并根据需要手动调整远程桌面的大小
        //     // 您可以在此处添加自定义逻辑以更好地控制远程桌面的大小
        // });

        function clipboardReceive(e) {
            Log.Debug(">> UI.clipboardReceive: " + e.detail.text.substr(0, 40) + "...");
            document.getElementById('noVNC_clipboard_text').value = e.detail.text;
            Log.Debug("<< UI.clipboardReceive");
        }

        function clipboardSend() {
            const text = document.getElementById('noVNC_clipboard_text').value;
            Log.Debug(">> UI.clipboardSend: " + text.substr(0, 40) + "...");
            rfb.clipboardPasteFrom(text);
            Log.Debug("<< UI.clipboardSend");
            closeClipboardPanel();
        }
    </script>
</head>

<body>
    <div id="top_bar">
        <div id="status">Loading</div>
        <div id="clipboard" style="right: 130px;">剪贴板</div>
        <!-- <div id="sendCtrlAltDelButton">Send Ctrl+Alt+Del</div> -->
    </div>
    <!-- noVNC Control Bar -->
    <div id="noVNC_control_bar_anchor" class="noVNC_vcenter">

        <div id="noVNC_control_bar">
            <div id="noVNC_control_bar_handle" title="Hide/Show the control bar">
                <div></div>
            </div>

            <div class="noVNC_scroll">

                <!-- Clipboard -->
                <div class="noVNC_vcenter">
                    <div id="noVNC_clipboard" class="noVNC_panel">
                        <div class="flex-row-between">
                            <p style="color: #333333; font-size: 22px;">剪贴板</p>
                            <img id="close" alt="" src="app/images/icons/close.png" style="cursor: pointer;" />
                        </div>
                        <div style="color: #FF6200; font-size: 16px;">
                            命令文本内容不能包含中文字符，且当命令包含换行符时，粘贴后可能会直接执行。
                        </div>
                        <textarea id="noVNC_clipboard_text" rows=5></textarea>
                        <div class="flex-row-end" style="width: 100%; gap: 30px; margin-top: 80px;">
                            <!-- <div id="info-btn" class="info-btn" onclick="toggleClipboardPanel()">取消</div> -->
                            <div id="main-btn" class="main-btn">确认</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div> <!-- End of noVNC_control_bar -->
    <div id="screen">
        <!-- This is where the remote screen will appear -->
    </div>
</body>

</html>